package com.zgx.plus.system.biz;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.google.code.kaptcha.Producer;
import com.zgx.plus.common.config.NacosConfig;
import com.zgx.plus.common.constant.ComConstant;
import com.zgx.plus.common.constant.RedisConstant;
import com.zgx.plus.common.redis.RedisCache;
import com.zgx.plus.common.response.R;
import com.zgx.plus.system.service.SysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.FastByteArrayOutputStream;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 验证码生成
 */
@Component
public class KaptchaService {

    @Resource(name = "captchaProducer")
    private Producer captchaProducer;
    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private NacosConfig nacosConfig;
    @Autowired
    private SysConfigService sysConfigService;

    /**
     * 验证码生成
     * ①、查询是否需要验证码配置
     * ②、根据验证码类型生成不同的验证码(文字或者算术)
     */
    public R<Map<String, Object>> captchaImage() {
        String captchaVal = sysConfigService.fetchConfigByKey("sys.account.captchaEnabled");
        boolean captchaEnabled = StrUtil.equalsIgnoreCase("true", captchaVal);
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("captchaEnabled", captchaEnabled);
        if (!captchaEnabled) {
            return R.ok(retMap);
        }

        String code = null;
        BufferedImage image = null;

        //        生成验证码
        String captchaType = nacosConfig.getCaptchaType();
        if ("math".equals(captchaType)) {
            String capText = captchaProducerMath.createText();
            String capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        } else if ("char".equals(captchaType)) {
            String capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }
        //        保存验证码信息
        String uuid = IdUtil.fastUUID();
        String verifyKey = StrUtil.concat(true, RedisConstant.REDIS_KEY_CAPTCHA_CODE, uuid);

        redisCache.setCacheObject(verifyKey, code, ComConstant.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        //        转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(Objects.requireNonNull(image), "gif", os);
        } catch (IOException e) {
            return R.fail(e.getMessage());
        }
        retMap.put("uuid", uuid);
        retMap.put("img", Base64.encode(os.toByteArray()));
        return R.ok(retMap);
    }
}
